<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\cache\driver\Redis;
class Salelogistor extends Auth
{

	public function __construct(Request $request){
        parent::__construct($request);
        $this->data = $request->param();
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->getChildIDdata = [];
        $this->saleModel = model('SaleModel');
        $this->AdminWarehouse_id = $this->saleModel->getAdminWarehouse($this->user_id);
    }

    // 
    public function list(Request $request){
        // ('sale_delivery_type_1', 'zh', '自取'),
        // ('sale_delivery_type_2', 'zh', '送货上门（本区）'),
        // ('sale_delivery_type_3', 'zh', '送货上门（本市）'),
        // ('sale_delivery_type_4', 'zh', '物流派送'),

        if(isset($this->data['request']) && $this->data['request'] == 'requestAjax'){
            $page = "1,1000000";
            $returnData['pageSum'] = 0;
            $returnData['page'] = 1;
            $pageSize = 1000000;
            if(isset($this->data['page']) && isset($this->data['pageSize'])){
                $page = $this->data['page'].','.$this->data['pageSize'];
                $returnData['page'] = $this->data['page'];
                $pageSize = $this->data['pageSize'];
            }
            
            $returnData['page'] = 1;
            if(isset($this->data['page']) && isset($this->data['pageSize'])){
                $returnData['page'] = $this->data['page'];
            }
            $where = [];
            $where['m.package_at'] = ['gt',0];
            $where['m.delivery_at'] = 0;
            $where['zu.warehouse_id'] = $this->AdminWarehouse_id;
            $where['zu.del_at'] = 0;


            if(isset($this->data['searchText']) && $this->data['searchText']){
                $where['zu.id|c.name'] = ['like','%'.$this->data['searchText'].'%'];
            }

            if($this->data['is_selfWork'] == 1){
                $where['zu.create_id'] = $this->user_id; 
                $returnData['pageSum'] = $this->getPageSum($this->data['requestType'],$this->AdminWarehouse_id,$this->user_id);
            } else{
                $returnData['pageSum'] = $this->getPageSum($this->data['requestType'],$this->AdminWarehouse_id);
            }

            if($this->data['requestType'] == 'self_fetching') $where['zu.delivery_type_id'] = 1;  
            if($this->data['requestType'] == 'this_area') $where['zu.delivery_type_id'] = 2;  
            if($this->data['requestType'] == 'this_city') $where['zu.delivery_type_id'] = 3;  
            if($this->data['requestType'] == 'logistor') $where['zu.delivery_type_id'] = 4;  
            if($this->data['requestType'] == 'delivery'){
                $where['m.delivery_at'] = ['gt',0];
                $where['m.receive_at'] = 0;
            }
            if($this->data['requestType'] == 'finish'){
                $where['m.delivery_at'] = ['gt',0];
                $where['m.receive_at'] = ['gt',0];
            } 

            $list = $this->getList($where,$page);
            $returnData['list'] = $list['list'];
            // dump($returnData);die;
            return json_encode(array('status'=>1,'data'=>$returnData));
        }else if( isset($this->data['requestType']) && $this->data['requestType'] == 'getLogistorCompany'){
            return json_encode($this->getCompanyLink($this->data['company_id'],$this->lang));
        }else if( isset($this->data['requestType']) && $this->data['requestType'] == 'cueCount'){   // 获取提示数
            return json_encode($this->cueCount());
        }else{
            return view('list',['isshow'=>1]);
        }
    }

    function getList($where,$page)
    {   
        $join = [
                    ['company c','zu.co_id = c.id','LEFT'], // 获取公司name
                    ['company b','zu.co_branch_id = b.id','LEFT'], // 获取公司name
                    ['company t','zu.trans_id = t.id','LEFT'],  // 获取分公司name
                    ['sale_make m','zu.id = m.sale_id'],
                    ['sale_invoice i','zu.id = i.sale_id','LEFT'],
                ];

        $field = ['zu.*,c.name company_name,b.name co_branch_name,t.name trans_name,m.id make_id,m.checker_id,m.create_at checker_at,m.create_id makeCreate_id,m.package_at,m.delivery_at make_delivery_at,i.drawer_id invoiceDrawer_id,i.drawer_at invoiceDrawer_at,i.number invoiceNumbert'];

        $data = getSearch('sale','zu',$field,$where,$join,'zu.priority desc','','',$page);
        if(!empty($data)){
            foreach ($data as $k => $v) {
                $data[$k]['delivery_type_name'] = getValue('multi_lang',['mkey'=>'sale_delivery_type_'.$v['delivery_type_id'],'lang'=>$this->lang],'content');
                
                $detail = $this->getSaleDetail($v['id']);
                $data[$k]['sale_detail'] = $detail['detail'];
                $data[$k]['sum_m3'] = $detail['sum_m3'];
                $data[$k]['sum_kgs'] = $detail['sum_kgs'];
                // 配单主管
                $data[$k]['makeCreate_name'] =  getValue('admin',['id'=>$v['makeCreate_id']],'nickname');
                // 对货员
                $data[$k]['checker_name'] =  getValue('admin',['id'=>$v['checker_id']],'nickname');
                $data[$k]['checker_time'] =  getTimeDates($v['checker_at'],$this->lang); 
                // 装箱完成时间
                $data[$k]['package_time'] =  getTimeDates($v['package_at'],$this->lang); 
                // 开票员/开票时间
                $data[$k]['invoiceDrawer_name'] =  getValue('admin',['id'=>$v['invoiceDrawer_id']],'nickname');
                $data[$k]['invoiceDrawer_time'] =  getTimeDates($v['invoiceDrawer_at'],$this->lang); 
                // 装箱信息
                $sale_pack = $this->getSalePack($v['id']);
                $data[$k]['salePackKgs'] = $sale_pack['salePackKgs'];
                $data[$k]['sale_pack'] = $sale_pack['sale_pack'];
                $data[$k]['salePackArea_name'] = getValue('warehouse_area',['id'=>$data[$k]['sale_pack'][0]['area_id']],'name');
                // 装箱员/装箱时间
                $data[$k]['salePackCreate_name'] = getValue('admin',['id'=>$data[$k]['sale_pack'][0]['create_id']],'nickname');
                $data[$k]['salePackCreate_time'] =  getTimeDates($data[$k]['sale_pack'][0]['create_at'],$this->lang); 
                // 获取公司信息
                $companyData = $this->getCompanyInfo($v['co_id'],$v['co_branch_id']);
                $data[$k]['companyInfo'] = $companyData['co_data'];
                $data[$k]['co_branch_info'] = $companyData['co_branch_data'];

                if($v['delivery_type_id'] == 4){
                    if($v['trans_id']){ 
                        $data[$k]['logistorCompany'] = $this->getCompanyInfo($v['trans_id']);
                    }else{
                        $data[$k]['logistorCompany'] = [];
                    }    
                    $aa = $this->getCompanyLink($v['trans_id'],$this->lang);
                    $data[$k]['logistorLink'] = $aa['link'];
                    $data[$k]['logistorAttr'] = $aa['attr'];

                    $make_logistics = getdatas('make_logistics',['*'],['sale_id'=>$v['id'],'call_at'=>['gt',0]]);
                    if(!empty($make_logistics)){
                        $data[$k]['is_logistorPickup'] = $make_logistics[0]['id'];
                        $data[$k]['logistorRemark'] = getValue('make_logistics_remark',['logistics_id'=>$data[$k]['is_logistorPickup']],'remark');
                        $data[$k]['logistorPickuTime'] = $make_logistics[0]['receive_at'] ? getTimeDates($make_logistics[0]['receive_at'],$this->lang) : '-'; 
                        $data[$k]['logistorPickuNo'] = $make_logistics[0]['number'] ? $make_logistics[0]['number'] : '-' ;
                        $data[$k]['logistorCtreateTime'] = getTimeDates($make_logistics[0]['create_at'],$this->lang); 
                        $data[$k]['logistorUpdateTime'] = $make_logistics[0]['update_at'] ? getTimeDates($make_logistics[0]['update_at'],$this->lang) :'-'; 
                    }
                    
                }
                

                $data[$k]['delivery_note_id'] = getValue('delivery_note',['sale_id'=>$v['id']],'id');

                // 实习送货员职位  人员
                $data[$k]['Intern_deliveryman'] = array_column(getdatas('admin',['id'],['position_id'=>39]), 'id');

                // 获取队员
                if($this->data['requestType'] == 'delivery' || $this->data['requestType'] == 'finish'){
                    $data[$k]['teams'] = $this->getTeams($v['id'],$v['delivery_type_id']);

                    if($v['make_delivery_at'] >0){
                        if(in_array($v['delivery_type_id'],[1,2,3])){ 
                            $data[$k]['make_delivery_start_at'] = getValue('make_delivery_detail',['sale_id'=>$v['id']],'start_at');
                        }else if($v['delivery_type_id'] == 4){
                            $data[$k]['make_delivery_start_at'] = getValue('make_logistics',['sale_id'=>$v['id']],'start_at');
                        }
                    }

                    $data[$k]['user_time'] = gmdate('H:i:s', time() - $data[$k]['make_delivery_start_at']);
                    $data[$k]['make_delivery_start_time'] = getTimeDates($data[$k]['make_delivery_start_at'],$this->lang);
                }
                
            }
        }
        $return['list'] = $data;
        
        return $return;
    }

    function getPageSum($requestType,$warehouse_id,$user_id=0)
    {
        $where['warehouse_id'] = $warehouse_id;
        $where['del_at'] = 0;

        if($user_id) $where['create_id'] = $user_id;

        if($requestType == 'self_fetching') $where['delivery_type_id'] = 1;  
        if($requestType == 'this_area') $where['delivery_type_id'] = 2;  
        if($requestType == 'this_city') $where['delivery_type_id'] = 3;  
        if($requestType == 'logistor') $where['delivery_type_id'] = 4; 

        if($requestType == 'delivery'){
            $where_['delivery_at'] = ['gt',0];
            $where_['receive_at'] = 0;
        }else if($requestType == 'finish'){
            $where_['delivery_at'] = ['gt',0];
            $where_['receive_at'] = ['gt',0];
        }else{
            $where_['package_at'] = ['gt',0];
            $where_['delivery_at'] = 0;
        }
        $pageSum = Db::name('sale')
                        ->where('id', 'IN', function ($query) use ($where_) {
                            $query->name('sale_make')->where($where_)->field('sale_id');
                        })
                        ->where($where)
                        ->count();
        return $pageSum;
    }

    // 获取队员
    function getTeams($sale_id,$delivery_type_id)
    {
        if(in_array($delivery_type_id,[1,2,3])){ 
            $table_ = 'make_delivery_team';
            $delivery_id = getValue('make_delivery_detail',['sale_id'=>$sale_id],'delivery_id');
            $where_ = ['delivery_id'=>$delivery_id];

        }else if($delivery_type_id == 4){
            $table_ = 'make_logistics_team';
            $logistics_id = getValue('make_logistics',['sale_id'=>$sale_id],'id');
            $where_ = ['logistics_id'=>$logistics_id];
        }

        $teams = Db::name('admin')
                    ->field(['id,nickname,position_id'])
                    ->where('id', 'IN', function ($query) use ($table_,$where_) {
                        $query->name($table_)->where($where_)->field('admin_id');
                    })
                    ->select();
        return $teams;
    }

    function getSaleDetail($sale_id)
    {
        $detail = getdatas('sale_detail',['*'],['sale_id'=>$sale_id]);
        $sum_m3 = 0;
        $sum_kgs = 0;
        foreach ($detail as $k => $v) {
            $detail[$k]['proInfo'] = getProAndProchar($v,$this->lang,48);
            $where['sale_id'] = $sale_id;
            $where['pro_id'] = $v['pro_id'];
            $where['prochar_id'] = $v['prochar_id'];
            $detail[$k]['pickupArea_name'] = Db::name('warehouse_area')
                                                ->where('id', 'IN', function ($query) use ($where) {
                                                    $query->name('make_pickup_detail')->where($where)->field('area_id');
                                                })
                                                ->value('name');
            $sum_m3  = $v['qty']/$detail[$k]['proInfo']['prochar_qty']*$detail[$k]['proInfo']['ctn_m3'];
            $sum_kgs = $v['qty']/$detail[$k]['proInfo']['prochar_qty']*$detail[$k]['proInfo']['ctn_kgs'];
        }
        $returnData['detail'] = $detail;
        $returnData['sum_m3'] = $sum_m3;
        $returnData['sum_kgs'] = $sum_kgs;
        return $returnData;
    }

    function getSalePack($sale_id)
    {
        $data = getdatas('sale_pack',['*'],['sale_id'=>$sale_id]);
        $salePackKgs = 0;
        if(!empty($data)){
            foreach ($data as $k => $v) {
                $data[$k]['detail'] = getdatas('sale_pack_detail',['*'],['pack_id'=>$v['id']]);
                if(!empty($data[$k]['detail'])){
                    foreach ($data[$k]['detail'] as $k1 => $v1) {
                        $data[$k]['detail'][$k1]['proInfo'] = getProAndProchar($v1,$this->lang,48);
                    }
                }
                $data[$k]['detail'][$k1]['remark'] = getdatas('sale_pack_remark',['id,remark'],['pack_id'=>$v['id']]);

                $salePackKgs += ($v['kgs']*$v['ctns']);
            }
        }
        $returnData['sale_pack'] = $data;
        $returnData['salePackKgs'] = $salePackKgs;
        return $returnData;
    }

    function getCompanyInfo($co_id,$co_branch_id=0)
    {
        $co_data = Db::name('co_profile')->where(['co_id'=>$co_id])->find();
        $co_data['town'] = getValue('town',['id'=>$co_data['town_id']],'name');
        $co_data['city'] = getValue('city',['id'=>$co_data['city_id']],'name');
        $co_data['province'] = getValue('provinces',['id'=>$co_data['province_id']],'name');
        if($co_branch_id){
            $co_branch_data = Db::name('co_branch')->where(['id'=>$co_branch_id])->find();
            $co_branch_data['town'] = getValue('town',['id'=>$co_branch_data['town_id']],'name'); 
            $co_branch_data['city'] = getValue('city',['id'=>$co_branch_data['city_id']],'name');
            $co_branch_data['province'] = getValue('provinces',['id'=>$co_branch_data['province_id']],'name');   
        }else{
            $co_branch_data = [];
        }
        $returnData['co_data'] = $co_data;
        $returnData['co_branch_data'] = $co_branch_data;
        return $returnData;

    }

    function cueCount()
    {

        $where_['package_at'] = ['gt',0];
        $where_['delivery_at'] = 0;

        $whereAnd = [];
        if(isset($this->data['is_selfWork']) && $this->data['is_selfWork'] == 1) $whereAnd['create_id'] = $this->user_id;

        // 自取
        $return['sellfCount'] = Db::name('sale')
                                ->where('id', 'IN', function ($query) use ($where_) {
                                    $query->name('sale_make')->where($where_)->field('sale_id');
                                })
                                ->where(['delivery_type_id'=>1,'del_at'=>0,'warehouse_id'=>$this->AdminWarehouse_id])
                                ->where($whereAnd)
                                ->count();
        // 本区
        $return['areaCount'] = Db::name('sale')
                                ->where('id', 'IN', function ($query) use ($where_) {
                                    $query->name('sale_make')->where($where_)->field('sale_id');
                                })
                                ->where(['delivery_type_id'=>2,'del_at'=>0,'warehouse_id'=>$this->AdminWarehouse_id])
                                ->where($whereAnd)
                                ->count();
        // 本市
        $return['cityfCount'] = Db::name('sale')
                                ->where('id', 'IN', function ($query) use ($where_) {
                                    $query->name('sale_make')->where($where_)->field('sale_id');
                                })
                                ->where(['delivery_type_id'=>3,'del_at'=>0,'warehouse_id'=>$this->AdminWarehouse_id])
                                ->where($whereAnd)
                                ->count();
        // 物流
        $return['logistorfCount'] = Db::name('sale')
                                    ->where('id', 'IN', function ($query) use ($where_) {
                                        $query->name('sale_make')->where($where_)->field('sale_id');
                                    })
                                    ->where(['delivery_type_id'=>4,'del_at'=>0,'warehouse_id'=>$this->AdminWarehouse_id])
                                    ->where($whereAnd)
                                    ->count();
              
        // 已送货
        $deliveryCountWhere['delivery_at'] = ['gt',0];
        $deliveryCountWhere['receive_at'] = 0;
        $return['deliveryCount'] = Db::name('sale')
                                    ->where('id', 'IN', function ($query) use ($deliveryCountWhere) {
                                        $query->name('sale_make')->where($deliveryCountWhere)->field('sale_id');
                                    })
                                    ->where(['del_at'=>0,'warehouse_id'=>$this->AdminWarehouse_id])
                                    ->where($whereAnd)
                                    ->count();

        // 已完成
        $finishCountWhere['delivery_at'] = ['gt',0];
        $finishCountWhere['receive_at'] = ['gt',0];
        $return['finishCount'] = Db::name('sale')
                                    ->where('id', 'IN', function ($query) use ($finishCountWhere) {
                                        $query->name('sale_make')->where($finishCountWhere)->field('sale_id');
                                    })
                                    ->where(['del_at'=>0,'warehouse_id'=>$this->AdminWarehouse_id])
                                    ->where($whereAnd)
                                    ->count();
        // dump($return);die;

        return $return;
    }

    // 自取 -- 取货
    function selfLogistorPickup()
    {
        if($this->data['requestType'] == 'getDeliveryman'){
            return json_encode($this->getDeliveryman());
        }else if($this->data['requestType'] == 'save'){
            return json_encode($this->saveMakeDelivery());
        }
    }

    // 获取送货人员
    function getDeliveryman($type=true)
    {
        if($type){
           $where = [
                    'zu.warehouse_id'=>$this->AdminWarehouse_id,
                    'zu.status'=>0,
                ]; 
        }else{
            $where = ['zu.warehouse_id'=>$this->AdminWarehouse_id]; 
        }
        
        $join = [
                    ['admin a','zu.admin_id = a.id']
                ];
        $data = getSearch('deliveryman','zu',['zu.*,a.position_id,a.nickname'],$where,$join,'zu.id desc');
        if(!$type){
            foreach ($data as $k => $v) {

                if($v['status'] == 1){
                    $aa = time() - $v['start_at'];
                    $data[$k]['work_time'] =  date('H:i:s',$aa);
                }
                if($v['status'] == 2){
                    $aa = time() - $v['leave_at'];
                    $data[$k]['leave_time'] =  date('H:i:s',$aa);
                }
                if($v['status'] == 3){
                    $aa = time() - $v['workout_at'];
                    $data[$k]['workout_time'] =  date('H:i:s',$aa);
                }
            }
        }
        
        // dump($data);die;
        unset($this->data['requestType']);
        return $data;
    }

    // 保存取货信息
    function saveMakeDelivery()
    {
        $deliverymanData['warehouse_id'] = $this->data['warehouse_id'];
        $deliverymanData['logistor_id'] = $this->user_id;

        $deliverymanData['start_at'] = time();
        $deliverymanData['finish_at'] = 0;

        $deliverymanData['create_id'] = $this->user_id;
        $deliverymanData['create_at'] = time();
        $deliverymanData['update_id'] = $this->user_id;
        $deliverymanData['update_at'] = time();

        $deliverymanData['start_at'] = $this->data['warehouse_id'];

        $deliverymanData['ctn'] = $this->data['ctn'];
        $deliverymanData['kgs'] = $this->data['salePackKgs'];
        $deliverymanData['m3'] = $this->data['volume'];

        $delivery_id = insertData('make_delivery',$deliverymanData);
        if($delivery_id){
            // 添加送货详情数据
            $make_delivery_detail['delivery_id'] = $delivery_id;
            $make_delivery_detail['co_id'] = $this->data['co_id'];
            $make_delivery_detail['sale_id'] = $this->data['sale_id'];
            $make_delivery_detail['make_id'] = $this->data['make_id'];
            $make_delivery_detail['warehouse_id'] = $this->data['warehouse_id'];
            $make_delivery_detail['delivery_type'] = $this->data['delivery_type'];
            $make_delivery_detail['delivery_note_id'] = $this->data['delivery_note_id'] ? $this->data['delivery_note_id'] :0;
            $make_delivery_detail['start_at'] = time();
            $make_delivery_detail['receive_at'] = 0;
            $make_delivery_detail['ctn'] = $this->data['ctn'];
            $make_delivery_detail['kgs'] = $this->data['salePackKgs'];
            $make_delivery_detail['m3'] = $this->data['volume'];
            $make_delivery_detail = insertData('make_delivery_detail',$make_delivery_detail);


            $make_delivery_team['delivery_id'] = $delivery_id;
            $make_delivery_team['warehouse_id'] = $this->data['warehouse_id'];
            if(isset($this->data['deliveryman_ids'])){
                foreach ($this->data['deliveryman_ids'] as $k => $v) {
                    // 添加送货小组数据
                    $position_id = getValue('admin',['id'=>$v],'position_id');
                    $make_delivery_team = insertData('make_delivery_team',['delivery_id'=>$delivery_id,'warehouse_id'=>$this->data['warehouse_id'],'admin_id'=>$v,'position_id'=>$position_id]);
                    // 编辑送货人员的当前状态
                    $deliveryman['status'] = 1;
                    $deliveryman['start_at'] = time();
                    updateData('deliveryman',['admin_id'=>$v],$deliveryman);

                }
            }

            // 编辑配货单状态为 已送货
            $res = updateData('sale_make',['sale_id'=>$this->data['sale_id']],['delivery_at'=>time()]);
            $this->saleModel->addSaleLog($this->data['sale_id'],'makeDelivery','自取完成');
            if($res){

                return array('status'=>1,'msg'=>'通知取货成功');
            }else{
                return array('status'=>1,'msg'=>'通知取货失败');
            }
        }else{
            return array('status'=>1,'msg'=>'通知取货失败');
        }

    }

    // 已安排 --完成
    function selfFetchingOK()
    {

        // 协助人员（自取/物流送货）速度=任务时长/任务数量
        // 本区送货速度=任务时长*60% /任务数量 
        // 本市送货（取货）速度=任务时长*25% /任务数量 
        // *注意个人速度只除任务数量不除以参与人员的数量

        // 个人平均箱数=任务速度 /箱数 /参与人员的数量
        // 个人平均重量=任务速度 /重量 /参与人员的数量
        // 个人平均立方=任务速度 /立方 /参与人员的数量
        return $this->organizeDelivery();
    }

    function organizeDelivery()
    {

        // $this->data['areaOrcity']

        if(in_array($this->data['delivery_type'],[1,2,3])){
            $delivery_id = getValue('make_delivery_detail',['sale_id'=>$this->data['sale_id']],'delivery_id');

            $make_delivery_detail['receive_at'] = time();
            $make_delivery_detail['receipt'] = $this->data['receipt'];
            $make_delivery_detail['receipt_id'] = $this->data['receipt_id'];
            $make_delivery_detail['speed'] = time() - $this->data['make_delivery_start_at'];
            // dump($this->data['teams']);die;
            $delivery_id = updateData('make_delivery_detail',['sale_id'=>$this->data['sale_id']],$make_delivery_detail);

            // 判断是否全部已完成 
            $delivery_detail_count = hasData('make_delivery_detail',['delivery_id'=>$delivery_id,'receive_at'=>0]);
            if(!$delivery_detail_count){
                // 获取同一个delivery_id 下的每个detail 的完成时间（speed） ，计算delivery_id平均时间（speed）
                $data = getdatas('make_delivery_detail',['*'],['delivery_id'=>$delivery_id,'receive_at'=>['gt',0]]);
                $time_sum = 0;
                foreach ($data as $k => $v) {
                    $time_sum += $v['speed'];
                }
                $speed = ceil($time_sum/count($data));

                // 协助人员（自取/物流送货）速度=任务时长/任务数量
                // 本区送货速度=任务时长*60% /任务数量 
                // 本市送货（取货）速度=任务时长*25% /任务数量 
                if($this->data['areaOrcity'] == 'area'){
                    $speed = $speed*0.6;
                }elseif($this->data['areaOrcity'] == 'city'){
                    $speed = $speed*0.25;
                }
                updateData('make_delivery',['id'=>$delivery_id],['finish_at'=>time(),'speed'=>$speed]);

                if(isset($this->data['teams']) && !empty($this->data['teams'])){
                    $this->organizeDeliveryman($this->data['teams'],$time_sum,'make_delivery',$delivery_id);
                }
            }
        }

        $res = updateData('sale_make',['id'=>$this->data['make_id']],['receive_at'=>time()]);
        $this->saleModel->addSaleLog($this->data['sale_id'],'makeDelivery','取货/送货已完成');
        if($res){
            return json_encode(array('status'=>1,'msg'=>'取货/送货成功'));
        }else{
            return json_encode(array('status'=>2,'msg'=>'取货、送货失败'));
        }
    }

    // 整理送货人员任务记录
    function organizeDeliveryman($teams,$time_sum,$table,$table_id)
    {   
        $team_sum = count($teams);
        $WarehouseModel = model('Warehouse');
        foreach ($teams as $k => $v) {
            // 获取一个任务的总工作时间和数量
            $tableData = Db::name($table)->where(['id'=>$table_id])->find();

            $ctn_ = $tableData['ctn']/$team_sum;
            $kgs_ = $tableData['kgs']/$team_sum;
            $m3_  = $tableData['m3'] /$team_sum;
            $working_ = floor($tableData['speed']/$team_sum);

            // 处理：make_delivery_team
            updateData('make_delivery_team',['delivery_id'=>$table_id,'admin_id'=>$v['id']],['speed'=>$working_,'ctn'=>$ctn_,'kgs'=>$kgs_,'m3'=>$m3_]);

            // 处理：deliveryman
            $deliverymanInfo = Db::name('deliveryman')->where(['admin_id'=>$v['id']])->find();
            $deliveryman['working'] =  $working_  + $deliverymanInfo['working'];
            $deliveryman['ctn'] = $ctn_ + $deliverymanInfo['ctn'];
            $deliveryman['kgs'] = $kgs_ + $deliverymanInfo['kgs'];
            $deliveryman['m3'] = $m3_ + $deliverymanInfo['m3'];
            $deliveryman['status'] = 0;

            $res = updateData('deliveryman',['admin_id'=>$v['id']],$deliveryman);
            if($res){
                $WarehouseModel->deliveryman_month($ctn_,$kgs_,$m3_,$working_,$v['id'],time());
            }
        }
    }

    function thisAreaDelivery()
    {   
        if($this->data['requestType'] == 'getDeliveryman'){
            return json_encode($this->getDeliveryman());
        }else if($this->data['requestType'] == 'save'){
            $res = $this->saveDeliveryman_($this->data['data'],$this->data['thisAreaDeliveryDataFooter'],$this->data['deliveryman_ids']);
            return json_encode( $res);
        }
    }

    // 保存送货名单
    function saveDeliveryman_($data,$thisAreaDeliveryDataFooter,$deliveryman_ids)
    {
        // $deliverymanData['warehouse_id'] = $data['warehouse_id'];
        $deliverymanData['logistor_id'] = $this->user_id;

        $deliverymanData['start_at'] = time();
        $deliverymanData['finish_at'] = 0;

        $deliverymanData['create_id'] = $this->user_id;
        $deliverymanData['create_at'] = time();
        $deliverymanData['update_id'] = $this->user_id;
        $deliverymanData['update_at'] = time();

        $deliverymanData['ctn'] = $thisAreaDeliveryDataFooter['ctn'];
        $deliverymanData['kgs'] = $thisAreaDeliveryDataFooter['kgs'];
        $deliverymanData['m3']  = $thisAreaDeliveryDataFooter['m3'];

        $delivery_id = insertData('make_delivery',$deliverymanData);
        if($delivery_id){
            // 添加送货详情数据
            foreach ($data as $k => $v) {
                $warehouse_id = $v['warehouse_id'];
                $make_delivery_detail = [
                                            'delivery_id'=>$delivery_id,
                                            'sale_id'=>$v['id'],
                                            'make_id'=>$v['make_id'],
                                            'warehouse_id'=>$v['warehouse_id'],
                                            'delivery_type'=>$v['delivery_type_id'],
                                            'm3'=>$v['volume'],
                                            'ctn'=>$v['ctn'],
                                            'kgs'=>$v['salePackKgs'],
                                            'start_at'=>time(),
                                            'receive_at'=>0,
                                            'co_id'=>$v['co_branch_id'] ? $v['co_branch_id'] : $v['co_id'] ,
                                            'delivery_note_id'=>$v['delivery_note_id'] ? $v['delivery_note_id'] : 0 ,
                                        ];

                $make_delivery_detail_ = insertData('make_delivery_detail',$make_delivery_detail);

                $make_delivery_team['delivery_id'] = $delivery_id;
                $make_delivery_team['warehouse_id'] = $v['warehouse_id'];

                // 编辑配货单状态为 已送货
                $res = updateData('sale_make',['id'=>$v['make_id']],['delivery_at'=>time()]);
                $this->saleModel->addSaleLog($v['id'],'makeDelivery','已安排送货');
            }

            updateData('make_delivery',['id'=>$delivery_id],['warehouse_id'=>$warehouse_id]);

            if(isset($deliveryman_ids)){
                foreach ($deliveryman_ids as $k1 => $v1) {
                    // 添加送货小组数据
                    $position_id = getValue('admin',['id'=>$v1],'position_id');
                    $make_delivery_team = insertData('make_delivery_team',['delivery_id'=>$delivery_id,'warehouse_id'=>$warehouse_id,'admin_id'=>$v1,'position_id'=>$position_id]);
                    // 编辑送货人员的当前状态
                    $deliveryman['status'] = 1;
                    $deliveryman['start_at'] = time();
                    updateData('deliveryman',['admin_id'=>$v1],$deliveryman);
                }
            }
            if($res){
                return array('status'=>1,'msg'=>'安排送货成功');
            }else{
                return array('status'=>1,'msg'=>'安排送货失败');
            }

        }else{
            return array('status'=>1,'msg'=>'安排送货失败');
        }

    }

    function thisAreaAndCityOK()
    {
        return $this->organizeDelivery();
    }

    function batchDelivery()
    {
        if($this->data['requestType'] == 'getDeliveryman'){
            return json_encode($this->getDeliveryman());
        }else if($this->data['requestType'] == 'save'){
            $res = $this->saveDeliveryman_($this->data['data'],$this->data['thisAreaDeliveryDataFooter'],$this->data['deliveryman_ids']);
            return json_encode($res);
        }
    }

    function getCompanyLink($co_id,$lang)
    {
        $join = [
                    ['linkman_method lm','zu.id = lm.linkman_id','LEFT'],
                    ['coattr c','lm.coattr_id = c.id','LEFT'],
                    ['multi_lang cm','c.mkey = cm.mkey','LEFT'],
                ];
        $where['zu.co_id'] = $co_id;
        $where['cm.lang'] = $lang;
        $data['link'] = getSearch('linkman','zu',['zu.id,lm.coattr_id,lm.content link_content,cm.content link_name'],$where,$join,'zu.id desc');

        $data['attr'] = getSearch('coattr_value','zu',['zu.*,cm.content attr_name'],['zu.co_id'=>$co_id,'cm.lang'=>$lang],[['coattr c','zu.coattr_id = c.id','LEFT'],['multi_lang cm','c.mkey = cm.mkey']],'zu.id desc');
        return $data;
    }

    // 获取物流公司
    function logistorNote()
    {   
        $data = [];
        if($this->data['requestType'] == 'main'){
            $data = getdatas('company',['*'],['type_id'=>4]);
        }else if($this->data['requestType'] == 'detail'){
            $data = $this->getCompanyLink($this->data['company_id'],$this->lang);
        }else if($this->data['requestType'] == 'save'){
            if( !hasData('make_logistics',['sale_id'=>$this->data['sale_id'],'receive_at'=>['gt',0]]) ){
                $make_logistics['m3'] = $this->data['m3'];
                $make_logistics['ctn'] = $this->data['ctn'];
                $make_logistics['kgs'] = $this->data['kgs'];
                $make_logistics['sale_id'] = $this->data['sale_id'];
                $make_logistics['make_id'] = $this->data['make_id'];
                $make_logistics['trans_id'] = $this->data['trans_id'];
                $make_logistics['warehouse_id'] = $this->data['warehouse_id'];
                $make_logistics['delivery_note_id'] = $this->data['delivery_note_id'];

                $make_logistics['call_id'] = $this->user_id;
                $make_logistics['call_at'] = time();
                $make_logistics['create_id'] = $this->user_id;
                $make_logistics['create_at'] = time();
                if(hasData('make_logistics',['sale_id'=>$this->data['sale_id']])){
                    $make_logistics['update_id'] = $this->user_id;
                    $make_logistics['update_at'] = time();
                    $res = updateData('make_logistics',['sale_id'=>$this->data['sale_id']],$make_logistics);
                    $make_logistics_id = $this->data['sale_id'];
                    $type = 'update';
                }else{
                    $make_logistics_id = insertData('make_logistics',$make_logistics);
                    $type = 'insert';
                }
                
                if($make_logistics_id){
                    if($this->data['remark']){
                        if($type == 'update'){
                            updateData('make_logistics_remark',['logistics_id'=>$make_logistics_id],['remark'=>$this->data['remark']]);
                        }else{
                            insertData('make_logistics_remark',['remark'=>$this->data['remark'],'logistics_id'=>$make_logistics_id]);
                        }
                    }
                    // 编辑销售单的物流ID
                    updateData('sale',['id'=>$this->data['sale_id']],['trans_id'=>$this->data['trans_id']]);
                    $data = array('status'=>1,'msg'=>'物流通知成功');
                }else{
                    $data = array('status'=>1,'msg'=>'物流通知失败');
                }
            }else{
                $data = array('status'=>1,'msg'=>'物流通知失败,物流已取货');
            }
        }
        return json_encode($data);
    }



    // 物流--取货
    function logistorPickup()
    {
        if($this->data['requestType'] == 'getDeliveryman'){
            return json_encode($this->getDeliveryman());
        }else if($this->data['requestType'] == 'save'){
            return json_encode($this->saveMakeLogistics());
        }
    }

    function saveMakeLogistics()
    {
        $make_logistics_id = getValue('make_logistics',['sale_id'=>$this->data['sale_id']],'id');
        $res = updateData('make_logistics',['sale_id'=>$this->data['sale_id']],['start_at'=>time()]);
        if($res){
            if(isset($this->data['deliveryman_ids'])){
                foreach ($this->data['deliveryman_ids'] as $k => $v) {
                    $position_id = getValue('admin',['id'=>$v],'position_id');

                    $insertData['logistics_id'] = $make_logistics_id;
                    $insertData['admin_id'] = $v;
                    $insertData['position_id'] = $position_id;

                    insertData('make_logistics_team',['warehouse_id'=>$this->data['warehouse_id'],'logistics_id'=>$make_logistics_id,'admin_id'=>$v,'position_id'=>$position_id]);

                    // 编辑送货人员的当前状态
                    $deliveryman['status'] = 1;
                    $deliveryman['start_at'] = time();
                    updateData('deliveryman',['admin_id'=>$v],$deliveryman);
                }
            }// 编辑配货单状态为 已送货
            $res1 = updateData('sale_make',['sale_id'=>$this->data['sale_id']],['delivery_at'=>time()]);
            $this->saleModel->addSaleLog($this->data['sale_id'],'makeDelivery','已安排物流');
            if($res1){
                return array('status'=>1,'msg'=>'物流取货开始 成功');
            }else{
                return array('status'=>1,'msg'=>'物流取货开始 失败');
            }
        }else{
            return array('status'=>2,'msg'=>'物流取货开始 失败');
        }
    }

    // 物流已取走
    function logistorPickupOK()
    {
        //make_delivery.speed/make_delivery.ctn/team
        if($this->data['requestType'] == 'getLogistorCompany' ){
            return json_encode($this->getCompanyLink($this->data['company_id'],$this->lang));
        }else if($this->data['requestType'] == 'getDeliveryman' ){
            return json_encode($this->getDeliveryman());
        }else if($this->data['requestType'] == 'save' ){

            $delivery_at = getValue('sale_make',['id'=>$this->data['make_id']],'delivery_at');
            if( (time()-$delivery_at)/3600 >= 72 ){

                $logisticsData = db::name('make_logistics')->where(['sale_id'=>$this->data['sale_id']])->find();
                $logisticsSpeed = time()-$logisticsData['start_at'];   // 任务用时
                $res = updateData('make_logistics',['id'=>$logisticsData['id']],['receive_id'=>$this->user_id,'receive_at'=>time(),'speed'=>$logisticsSpeed,'number'=>$this->data['logistorNo']]);
                if($res){
                    if(isset($this->data['teams'])){
                        $WarehouseModel = model('Warehouse');
                        $make_logistics_team['speed'] = $logisticsSpeed/count($this->data['teams']);
                        $make_logistics_team['ctn'] = $logisticsData['ctn']/count($this->data['teams']);
                        $make_logistics_team['kgs'] = $logisticsData['kgs']/count($this->data['teams']);
                        $make_logistics_team['m3']  = $logisticsData['m3'] /count($this->data['teams']);
                        updateData('make_logistics_team',['logistics_id'=>$logisticsData['id']],$make_logistics_team);

                        foreach ($this->data['teams'] as $k => $v) {

                            // 处理：deliveryman
                            $deliverymanInfo = Db::name('deliveryman')->where(['admin_id'=>$v['id']])->find();
                            $deliveryman['working'] =  $make_logistics_team['speed']  + $deliverymanInfo['working'];
                            $deliveryman['ctn'] = $make_logistics_team['ctn'] + $deliverymanInfo['ctn'];
                            $deliveryman['kgs'] = $make_logistics_team['kgs'] + $deliverymanInfo['kgs'];
                            $deliveryman['m3'] = $make_logistics_team['m3'] + $deliverymanInfo['m3'];
                            $deliveryman['status'] = 0;
                            $res = updateData('deliveryman',['admin_id'=>$v['id']],$deliveryman);
                            if($res){
                                $WarehouseModel->deliveryman_month($make_logistics_team['ctn'],$make_logistics_team['kgs'],$make_logistics_team['m3'],$make_logistics_team['speed'],$v['id'],time());
                            }
                        }
                    }
                    $res1 = updateData('sale_make',['sale_id'=>$this->data['sale_id']],['receive_at'=>time()]);
                    $res1 = updateData('sale',['sale_id'=>$this->data['sale_id']],['receive_at'=>time()]);
                    $this->saleModel->addSaleLog($this->data['sale_id'],'makeDelivery','物流已完成');
                    if($res1){
                        return json_encode(array('status'=>1,'msg'=>'物流取货完成'));
                    }else{
                        return json_encode(array('status'=>2,'msg'=>'物流取货失败'));
                    }
                }else{
                    return json_encode(array('status'=>2,'msg'=>'物流取货失败'));
                }
            }else{
                return json_encode(array('status'=>2,'msg'=>'物流取货失败，物流配送订单 要三天之后才能完成'));
            }
        }
    }

    // 送货人员 btn
    function deliverymanBtn()
    {
        if($this->data['requestType'] == 'getDeliveryman'){
            return json_encode($this->getDeliveryman(false));
        }
    }

    // 离岗
    function deliverymanWorkout()
    {
        if(isset($this->data['admin_id'])){
            if(hasData('deliveryman',['admin_id'=>$this->data['admin_id'],'status'=>1])){
                return json_encode(array('status'=>2,'msg'=>'送货员：'.$this->data['admin_name'].' 离岗失败，当前在工作中'));
            }else{
                $res = Db::name('deliveryman')->where(['id'=>$this->data['admin_id']])->update(['status'=>3,'workout_at'=>time()]);
                if($res){
                    return json_encode(array('status'=>1,'msg'=>'送货员：'.$this->data['admin_name'].' 离岗成功'));
                }else{
                    return json_encode(array('status'=>2,'msg'=>'送货员：'.$this->data['admin_name'].' 离岗失败'));
                }
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>'请选择正确送货员'));
        }
    }
    // 请假
    function deliverymanLeave()
    {
        if(isset($this->data['admin_id'])){
            if(hasData('deliveryman',['admin_id'=>$this->data['admin_id'],'status'=>1])){
                return json_encode(array('status'=>2,'msg'=>'送货员：'.$this->data['admin_name'].' 请假失败，当前在工作中'));
            }else{
                $res = Db::name('deliveryman')->where(['id'=>$this->data['admin_id']])->update(['status'=>2,'leave_at'=>time()]);
                if($res){
                    return json_encode(array('status'=>1,'msg'=>'送货员：'.$this->data['admin_name'].' 请假成功'));
                }else{
                    return json_encode(array('status'=>2,'msg'=>'送货员：'.$this->data['admin_name'].' 请假失败'));
                }
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>'请选择正确送货员'));
        }
    }

    //打印
    function prinf()
    {
        return 1;
    }
}
